from flask import current_app,g,redirect,render_template,request,jsonify
from flask import session

from info import db
from . import profile_blue
from info.utils.commons import login_required
from info.utils.response_code import RET


@profile_blue.route('/info')
@login_required
def user_info():

    user = g.user
    if not user:
        return redirect('/')


    data = {
        'user':user.to_dict()
    }

    return render_template('news/user.html',data = data)


@profile_blue.route('/base_info',methods=['GET','POST'])
@login_required
def base_info():

    user = g.user
    if request.method =='GET':

        data = {
            'user':user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)

    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')

    if gender not in ['MAN','WOMAN']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数格式错误')

    user.nick_name = nick_name
    user.signature =signature
    user.gender = gender

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')

    session['nick_name'] = nick_name

    return jsonify(errno=RET.OK,errmsg='OK')





